import { ref, onUnmounted } from "vue";

export function useSSE(baseUrl: string, onData: Function) {
    const eventSource = ref(null);
    const tableData = ref([]);
    const totalRecords = ref(0);
    const loading = ref(false);
    const BATCH_SIZE = 1000; // 定义批处理大小

    // 添加 stopSSE 方法
    const stopSSE = () => {
        if (eventSource.value) {
            eventSource.value.close();
            eventSource.value = null;
            // 清理数据
            tableData.value = [];
            totalRecords.value = 0;
        }
    };

    // 添加批处理方法
    const processBatchData = (newData: any[], callback: Function) => {
        const chunks = [];
        for (let i = 0; i < newData.length; i += BATCH_SIZE) {
            chunks.push(newData.slice(i, i + BATCH_SIZE));
        }

        chunks.forEach((chunk, index) => {
            setTimeout(() => {
                callback(chunk);
            }, index * 16); // 每16ms处理一批，保持60fps
        });
    };

    const startSSE = (params: Record<string, any>) => {
        try {
            loading.value = true;
            stopSSE();

            const requestUrl = new URL(baseUrl);
            Object.keys(params).forEach((key) => {
                requestUrl.searchParams.set(key, params[key].toString());
            });

            eventSource.value = new EventSource(requestUrl.toString());

            eventSource.value.onmessage = (event) => {
                const newData = JSON.parse(event.data);
                console.log("收到数据:", newData);

                if (newData.length === 0) {
                    console.log("✅ 数据接收完毕，关闭 SSE 连接");
                    eventSource.value?.close();
                    eventSource.value = null;
                } else {
                    // 修改批处理逻辑
                    processBatchData(newData.data, (chunk: any[]) => {
                        tableData.value = [...tableData.value, ...chunk];
                        // 每批数据都通知调用者
                        if (onData) {
                            onData(chunk, newData.totalRecords);
                        }
                    });
                    totalRecords.value = newData.totalRecords;
                }
            };

            eventSource.value.onerror = (error) => {
                console.error("❌ SSE 连接错误:", error);
                eventSource.value?.close();
                eventSource.value = null;
            };
        } catch (error) {
            console.error("SSE 连接失败:", error);
        } finally {
            loading.value = false;
        }
    };

    // 组件销毁时使用 stopSSE 方法
    onUnmounted(() => {
        stopSSE();
    });

    return { tableData, totalRecords, loading, startSSE, stopSSE };
}


// export interface SSEResponse<T> {
//     data: T;
//     currentPage: number;
//     totalPages: number;
//     totalRecords: number;
//     pageSize: number;
// }

